import thin_render from "../../../lib/thin_render.mjs";
import { thin } from "../../../thin3.mjs";
import validate from "../../../lib/validate.mjs";

/**
 * 渲染行操作按钮（插入/删除）
 * @param {Object} params - 渲染参数
 */
export function renderActionButton({ tr, template, mode, insert }) {
  if ((template.rowinsert || template.rowdelete) && mode === "edit") {
    let td = document.createElement("td");
    tr.appendChild(td);

    if (insert && template.rowinsert) {
      // 渲染插入按钮
      thin_render(td, {
        button: "insert",
        click: async (e) => {
          if (typeof template.rowinsert === "function") {
            validate({
              container: tr,
              valid: async () => {
                await template.rowinsert(e, () => {
                  const tbody = tr.closest("tbody");
                  const data = tbody.thin_rowdata;
                  data.push({ ...e.new_data, ...e.org_data });
                  tbody.innerHTML = "";
                  template.rerender(tbody, data);
                  template?.inserted?.(e);
                });
              },
              invalid: () => {
                e.done();
              },
            });
          } else if (template.rowinsert === true) {
            await handleInsert(tr, template, e);
          }
        },
      });
    } else if (!insert && template.rowdelete) {
      // 渲染删除按钮
      thin_render(td, {
        button: "delete",
        click: (e) => {
          if (typeof template.rowdelete === "function") {
            template.rowdelete(e, () => handleDelete(tr, template, e));
          } else if (template.rowdelete === true) {
            handleDelete(tr, template, e);
          }
          template?.deleted?.(e);
        },
      });
    }
  }
}

function handleDelete(tr, template, e) {
  let tbody = tr.closest("tbody");
  let d = tbody.thin_rowdata;
  d.splice(e.rowindex, 1);
  thin(tbody).empty();
  template.rerender(tbody, d);
}

async function handleInsert(tr, template, e) {
  if (template.rowinsert === true) {
    const tbody = tr.closest("tbody");
    const data = tbody.thin_rowdata;

    // 插入前钩子
    await template?.beforeinsert?.(e);

    validate({
      container: tr,
      valid: function () {
        data.push({ ...e.new_data, ...e.org_data });
        tbody.innerHTML = "";
        template.rerender(tbody, data);
        template?.inserted?.(e);
      },
      invalid: function () {
        e.done();
      },
    });
  }
}
